﻿using SHDM.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Http;

namespace SHDM.Web.Infrastructure
{
    public class ApiBaseController : ApiController
    {
        private const string HttpContext = "MS_HttpContext";
        private const string RemoteEndpointMessage =
            "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
        private const string OwinContext = "MS_OwinContext";

        public AccountInfo AccountInfo
        {
            get
            {
                var info = RequestContext.Principal.Identity as HIdentity;
                return info.AccountInfo;
            }
        }
      
        public string ClientIpAddress
        {
            get
            {
                // Web-hosting. Needs reference to System.Web.dll
                if (Request.Properties.ContainsKey(HttpContext))
                {
                    dynamic ctx = Request.Properties[HttpContext];
                    if (ctx != null)
                    {
                        return ctx.Request.UserHostAddress;
                    }
                }

                // Self-hosting. Needs reference to System.ServiceModel.dll. 
                if (Request.Properties.ContainsKey(RemoteEndpointMessage))
                {
                    dynamic remoteEndpoint = Request.Properties[RemoteEndpointMessage];
                    if (remoteEndpoint != null)
                    {
                        return remoteEndpoint.Address;
                    }
                }

                // Self-hosting using Owin. Needs reference to Microsoft.Owin.dll. 
                if (Request.Properties.ContainsKey(OwinContext))
                {
                    dynamic owinContext = Request.Properties[OwinContext];
                    if (owinContext != null)
                    {
                        return owinContext.Request.RemoteIpAddress;
                    }
                }

                return string.Empty;
            }
        }

        public virtual NLog.Logger Log
        {
            get
            {
                return NLog.LogManager.GetLogger("ApiController");
            }
        }
    }
}